<template>
  <view class="edit-page user-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms ref="formRef" :modelValue="form" :rules="rules" labelWidth="80px">
        <uni-forms-item label="用户名" name="userName" required v-if="pageType === 'add'">
          <uni-easyinput
              v-model="form.userName"
              placeholder="请输入用户名"
              maxlength="30"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="用户密码" name="password" required v-if="pageType === 'add'">
          <uni-easyinput
              v-model="form.password"
              type="password"
              placeholder="请输入用户密码"
              maxlength="20"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="用户昵称" name="nickName" required>
          <uni-easyinput
              v-model="form.nickName"
              placeholder="请输入用户昵称"
              maxlength="30"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="归属部门" name="deptId" required>
          <BottomTreeSelect
              v-model="form.deptId"
              :tree-data="deptTreeData"
              value-field="deptId"
              label-field="deptName"
              children-field="children"
              placeholder="请选择归属部门"
              title="选择部门"
              :disabled="!canEdit">
          </BottomTreeSelect>
        </uni-forms-item>

        <uni-forms-item label="手机号码" name="phonenumber">
          <uni-easyinput
              v-model="form.phonenumber"
              placeholder="请输入手机号码"
              maxlength="11"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="邮箱" name="email">
          <uni-easyinput
              v-model="form.email"
              placeholder="请输入邮箱"
              maxlength="50"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="用户性别" name="sex">
          <uni-data-checkbox
              v-model="form.sex"
              :localdata="sys_user_sex"
              mode="button"
              :map="{text:'label',value:'value'}"
              :disabled="!canEdit">
          </uni-data-checkbox>
        </uni-forms-item>

        <uni-forms-item label="状态" name="status">
          <uni-data-checkbox
              v-model="form.status"
              :localdata="statusOptions"
              mode="button"
              :disabled="!canEdit">
          </uni-data-checkbox>
        </uni-forms-item>

        <uni-forms-item label="岗位" name="postIds">
          <BottomSelect
              v-model="form.postIds"
              :options="postOptions"
              value-field="postId"
              label-field="postName"
              placeholder="请选择岗位"
              title="选择岗位"
              :multiple="true"
              :disabled="!canEdit">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="角色" name="roleIds">
          <uni-data-checkbox
              v-model="form.roleIds"
              :localdata="roleOptions"
              multiple
              :disabled="!canEdit">
          </uni-data-checkbox>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
              v-model="form.remark"
              type="textarea"
              placeholder="请输入内容"
              maxlength="500"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="goBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="submitForm">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, nextTick, onMounted, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addUser, getUser, updateUser} from '@/api/system/user'
import {listRole} from '@/api/system/role'
import {listPost} from '@/api/system/post'
import {listDept} from '@/api/system/dept'
import {useDict} from '@/utils/dict'
import {BottomSelect, BottomTreeSelect} from '@/components/select'
import {handleTree} from '@/utils/ruoyi'

const {proxy} = getCurrentInstance()

// 字典数据
const {sys_user_sex} = useDict('sys_user_sex')

// 页面参数
const pageType = ref('add')
const userId = ref(null)
const submitting = ref(false)

// 计算属性
const pageTitle = computed(() => {
  const title = (() => {
    switch (pageType.value) {
      case 'add':
        return '新增用户'
      case 'edit':
        return '编辑用户'
      case 'view':
        return '查看用户'
      default:
        return '用户管理'
    }
  })()

  return title
})

const isView = computed(() => pageType.value === 'view')
const canEdit = computed(() => pageType.value === 'add' || pageType.value === 'edit')

// 表单数据
const form = reactive({
  userId: undefined,
  deptId: undefined,
  userName: '',
  nickName: '',
  password: '123456',
  phonenumber: '',
  email: '',
  sex: '1',
  status: '0',
  remark: '',
  postIds: [],
  roleIds: []
})

// 表单验证规则
const rules = reactive({
  userName: {
    rules: [
      {required: true, errorMessage: '用户名不能为空'},
      {minLength: 2, maxLength: 20, errorMessage: '用户名长度应为2-20位'},
      {pattern: /^[a-zA-Z0-9_-]+$/, errorMessage: '用户名只能包含字母、数字、下划线和短横线'}
    ]
  },
  password: {
    rules: [
      {required: true, errorMessage: '用户密码不能为空'},
      {minLength: 5, maxLength: 20, errorMessage: '用户密码长度必须介于5和20之间'},
      {pattern: /^[^<>"'|\\]+$/, errorMessage: '不能包含非法字符：< > " \' \\ |'}
    ]
  },
  nickName: {
    rules: [
      {required: true, errorMessage: '用户昵称不能为空'},
      {minLength: 2, maxLength: 20, errorMessage: '用户昵称长度应为2-20位'}
    ]
  },
  deptId: {
    rules: [
      {required: true, errorMessage: '归属部门不能为空'}
    ]
  },
  email: {
    rules: [
      {format: 'email', errorMessage: '请输入正确的邮箱地址'}
    ]
  },
  phonenumber: {
    rules: [
      {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, errorMessage: '请输入正确的手机号码'}
    ]
  }
})

// 选项数据
const deptTreeData = ref([])
const roleOptions = ref([])
const postOptions = ref([])

const statusOptions = ref([
  {value: '0', text: '正常'},
  {value: '1', text: '停用'}
])

const formRef = ref()

// ==================== 关键修复：使用 onLoad 生命周期钩子 ====================
// 使用 onLoad 生命周期钩子接收页面参数，解决App端参数丢失问题
onLoad((options) => {
  // 直接从 onLoad 参数中获取页面参数，这在所有平台都是可靠的
  pageType.value = options.mode || options.type || 'add'
  userId.value = options.userId || options.id || null

  // 设置页面标题
  uni.setNavigationBarTitle({
    title: pageTitle.value
  })

  // 如果是编辑或查看模式且有用户ID，加载用户信息
  if ((pageType.value === 'edit' || pageType.value === 'view') && userId.value) {
    // 延迟一下确保页面完全初始化后再加载数据
    nextTick(() => {
      getUserInfo()
    })
  }
})

// 页面加载
onMounted(() => {
  // 加载基础数据
  getDeptTree()
  getRoleList()
  getPostList()
})

// 获取部门树
async function getDeptTree() {
  try {
    // 直接使用 listDept API，与 index.vue 页面保持一致
    const response = await listDept()
    if (response.code === 200) {
      deptTreeData.value = handleTree(response.data, 'deptId', 'parentId', 'children')
    }
  } catch (error) {
    console.error('获取部门树失败：', error)
  }
}

// 获取角色列表
async function getRoleList() {
  try {
    const response = await listRole()
    if (response.code === 200) {
      roleOptions.value = response.rows.map(item => ({
        value: item.roleId,
        text: item.roleName,
        disabled: item.status === '1'
      }))
    }
  } catch (error) {
    console.error('获取角色列表失败：', error)
  }
}

// 获取岗位列表
async function getPostList() {
  try {
    const response = await listPost()
    if (response.code === 200) {
      postOptions.value = response.rows.map(item => ({
        postId: item.postId,
        postName: item.postName,
        disabled: item.status === '1'
      }))
    }
  } catch (error) {
    console.error('获取岗位列表失败：', error)
  }
}

// 获取用户信息
async function getUserInfo() {
  try {
    const response = await getUser(userId.value)

    if (response.code === 200) {
      // 直接赋值用户基本信息
      Object.assign(form, response.data)

      // 编辑时清除密码字段，防止误操作
      if (pageType.value === 'edit') {
        form.password = ''
      }

      // 处理数组字段 - 检查不同的可能数据结构
      form.postIds = response.data.postIds || response.postIds || []
      form.roleIds = response.data.roleIds || response.roleIds || []

      // 处理部门ID
      if (response.data.dept && response.data.dept.deptId) {
        form.deptId = response.data.dept.deptId
      }

      // 更新岗位和角色选项（编辑时获取完整数据）
      if (response.data.posts || response.posts) {
        const posts = response.data.posts || response.posts || []
        postOptions.value = posts.map(item => ({
          postId: item.postId,
          postName: item.postName,
          disabled: item.status === '1'
        }))
      }

      if (response.data.roles || response.roles) {
        const roles = response.data.roles || response.roles || []
        roleOptions.value = roles.map(item => ({
          value: item.roleId,
          text: item.roleName,
          disabled: item.status === '1'
        }))
      }
    } else {
      console.error('获取用户信息失败:', response.msg)
      proxy.$modal.showToast(response.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息异常:', error)
    proxy.$modal.showToast('获取用户信息失败')
  }
}

// 提交表单
async function submitForm() {
  if (submitting.value) return

  try {
    // 表单验证
    await formRef.value.validate()

    submitting.value = true

    // 数据预处理
    const submitData = {...form}

    // 提交数据
    if (pageType.value === 'add') {
      await addUser(submitData)
      proxy.$modal.showToast('新增成功')
    } else {
      // 编辑时移除密码字段
      delete submitData.password
      await updateUser(submitData)
      proxy.$modal.showToast('修改成功')
    }

    // 返回上级页面
    setTimeout(() => {
      goBack()
    }, 1500)

  } catch (error) {
    console.error('提交失败：', error)
    if (error.errorFields) {
      proxy.$modal.showToast('请填写必填项')
    } else {
      proxy.$modal.showToast('操作失败')
    }
  } finally {
    submitting.value = false
  }
}

// 返回
function goBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import '@/styles/edit-page.scss';
</style>
